#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import getopt
import os
import re

from xml.dom.minidom import parse

def usage():
    print """\
Usage:

   %(progname)s [options]

where options are:
   -u, --user=username       SVN username to filter.
   -s, --rev_start=REVSTART  SVN start revision number.
   -e, --rev_end=REVEND      SVN end revision number, -1 for HEAD.
   -h, --help                this message
""" % { 'progname': sys.argv[ 0 ] }
    raise SystemExit
# usage()



def get_tag_contents( dom_element, tag_name ):
    r = []
    for c in dom_element.getElementsByTagName( tag_name ):
        for n in c.childNodes:
            if n.nodeType == n.TEXT_NODE:
                r.append( n.data )
    return "".join( r )
# get_tag_contents()




reformat_regexps = [
    ( re.compile( '(^| )TODO(:| |$)' ), "'''TO DO:'''\n" ),
    ( re.compile( '(^\s*)[-]' ), r'\1 *' ),
    ( re.compile( chr( 1 ) ), r' ' ),
    ( re.compile( '^\s+(\w)', re.UNICODE | re.DOTALL ), r'\1' ),
    ( re.compile( '\s*$' ), '' ),
    ]
def msg_reformat( msg ):
    lines = msg.split( '\n' )
    for i, l in enumerate( lines ):
        for regexp, replacement in reformat_regexps:
            lines[ i ] = regexp.sub( replacement, lines[ i ] )

    for i, l in enumerate( lines ):
        l = l.strip()

        if l.isspace():
            continue

        if l.strip().startswith( '*' ):
            lines.insert( i, "\n'''Changes:'''\n" )

        break

    i = 0
    while i < len( lines ):
        if i > 0 and lines[ i - 1 ].strip().startswith( '*' ) and \
           lines[ i ].strip() and \
           not lines[ i ].strip().startswith( '*' ) and \
           not lines[ i ].strip().isspace():
            lines[ i - 1 ] += " " + lines[ i ]
            del lines[ i ]
        i += 1

    return '\n'.join( lines )
# msg_reformat()







if __name__ == "__main__":

    url_base = 'http://ltc08.ic.unicamp.br/viewcvs/?root=mc705-python&rev=%(revision)s&view=rev'

    user = None
    rev_start = 0
    rev_end   = -1

    opts, args = getopt.getopt( sys.argv[ 1: ], 'u:s:e:h',
                                [ 'user=', 'author=', 'rev_start=',
                                  'rev_end=', 'help' ] )
    for opt, arg in opts:
        if   opt in ( '--user', '--author', '-u' ):
            user = arg
        elif opt in ( '-s', '--rev_start' ):
            try:
                rev_start = int( arg )
            except ValueError:
                print >> sys.stderr, 'REVSTART should be an integer!'
        elif opt in ( '-e', '--rev_end' ):
            try:
                rev_end = int( arg )
            except ValueError:
                print >> sys.stderr, 'REVEND should be an integer!'
        elif opt in ( '-h', '--help' ):
            usage()
        else:
            print >> sys.stderr, 'Option "%s" is not recognized!' % opt
    # for opt, arg in opts


    if rev_end > 0:
        rev_range = ( rev_start, rev_end )
    else:
        rev_range = ( rev_start, "HEAD" )

    xml = os.popen( "svn log -v --xml -r%s:%s" % rev_range )
    #xml = file( 'svn-log.xml' )

    dom = parse( xml )

    log = dom.documentElement

    for child in log.getElementsByTagName( 'logentry' ):
        revision = int( child.getAttribute( 'revision' ) )
        author = get_tag_contents( child, 'author' )

        if ( user is None or ( user is not None and author == user ) ) \
               and \
               ( revision >= rev_start and \
                 ( rev_end < 0 or
                   ( rev_end > 0  and revision < rev_end ) ) ):

            date = get_tag_contents( child, 'date' )
            msg  = msg_reformat( get_tag_contents( child, 'msg' ) )
            url  = url_base % { 'revision': revision }

            print """\
----
 * '''Revisao:''' %s
 * '''Data:''' %s
 * '''URL:''' %s

%s
""" % ( revision, date, url, msg )
